﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameNode
{
    class CleverNode : ConsoleNode
    {
        enum MoveDirection
        {
            Left,
            Right
        }

        private bool isOnTop;
        private bool isOnLeft;
        private MoveDirection direction;

        public CleverNode(int x, int y, char nodeSymbol, ConsoleColor color) : base(x, y, nodeSymbol, color)
        {
            direction = MoveDirection.Right;
        }
        public override void Move(Func<int, int, Position> positionFunction)
        {
            if (!isOnTop)
            {
                if (positionFunction(X, Y - 1) == Position.Free)
                {
                    MoveUp();
                }
                else if (positionFunction(X, Y - 1) == Position.Border)
                    isOnTop = true;
            }
            else if (!isOnLeft)
            {
                if (positionFunction(X - 1, Y) == Position.Free)
                {
                    MoveLeft();
                }
                else if (positionFunction(X - 1, Y) == Position.Border)
                    isOnLeft = true;
            }
            else if (isOnTop && isOnLeft)
            {
                if (direction == MoveDirection.Right)
                {
                    if (positionFunction(X + 1, Y) == Position.Free)
                    {
                        MoveRight();
                    }
                    else if (positionFunction(X + 1, Y) == Position.Border)
                    {
                        if (positionFunction(X, Y + 1) == Position.Free)
                        {
                            MoveDown();
                            direction = MoveDirection.Left;
                        }
                    }
                }
                else if (direction == MoveDirection.Left)
                {
                    if (positionFunction(X - 1, Y) == Position.Free)
                    {
                        MoveLeft();
                    }
                    else if (positionFunction(X - 1, Y) == Position.Border)
                    {
                        if (positionFunction(X, Y + 1) == Position.Free)
                        {
                            MoveDown();
                            direction = MoveDirection.Right;
                        }
                    }
                }
            }
        }
    }
}
